#!/bin/zsh

# Application details
app_path=$(mdfind 'kMDItemFSName == "Nudge.app"')
app_bundle=$(defaults read "${app_path}/Contents/Info.plist" CFBundleIdentifier)

# User details
current_user=$(stat -f%Su /dev/console)
user_id=$(id -u $current_user)

# Anyone logged in?
case $((
        (user_id >= 0 && user_id <= 500) * 1)) in
        (1) echo "No active user session"; unload_service=0;;
        (0) echo "Removing service for user: $user_id for bundle: $app_bundle"; unload_service=1;;
esac

if [ $unload_service -eq 1 ]
then
	echo "Is service loaded for $user_id gui/${user_id}/$app_bundle Unload service: $unload_service"

	launchctl asuser $user_id sudo -u $current_user launchctl print gui/${user_id}/$app_bundle &>/dev/null

	if [ $? -eq 0 ]
	then
		echo "Unloading gui/${user_id}/$app_bundle"
		launchctl asuser $user_id sudo -u $current_user launchctl bootout gui/${user_id}/$app_bundle
	fi
fi

# Logger may still be running
launchctl bootout system/com.github.macadmins.Nudge.Logger

# Remove any existing plist files
find /Users/*/Library/Preferences/${app_bundle}.plist -exec rm {} \;
find /Library/Launch* -name "${app_bundle}*" -exec rm {} \;

# Remove App
if [ "$app_path" ]
then
	rm -R "$app_path"
fi

pkgutil --forget com.github.macadmins.Nudge.Suite
pkgutil --forget com.github.macadmins.Nudge.LaunchAgent

exit 0